package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class CheckUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //拿到浏览器发送的请求验证码
        String code = request.getParameter("code");

        //通过会话对象拿到服务器存储的验证码
        String checkcode = (String) request.getSession().getAttribute("checkcode");

        //利用业务对象调用方法,判断用户在数据库是否存在
        boolean result = new UserService().checkUser(new User(null, username, password));

        //判断结果
        if (result && code.equals(checkcode)) {
            //如果为true,则说明登陆成功,跳转成功页面
            response.sendRedirect("/success.html");
        } else {
            //false跳转失败页面
            response.sendRedirect("/error.html");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
